package com.hongye.why.app;

import android.content.Context;
import android.text.TextUtils;

import com.hongye.why.model.Field;
import com.hongye.why.model.User;
import com.hongye.why.model.UserInfo;
import com.hongye.why.util.PreferenceUtil;

/**
 * 用户登录后保存信息
 */
public class YFUserSession {
    /**
     * 登录的当前用户
     */
    private User currentUser;
    private Context context;

    public YFUserSession(Context context) {
        this.context = context;
        currentUser = PreferenceUtil.getObj(context,"currentUser",User.class);
    }

    public void setUser(String account, String psd, String userToken) {
        currentUser = new User(account,psd,userToken);
        saveUser();
    }

    public void setUser(String account, String psd, String userToken, UserInfo userInfo, Field field) {
        currentUser = new User(account,psd,userToken);
        currentUser.userInfo = userInfo;
        currentUser.field = field;
        saveUser();
    }

    public void setUserInfo(UserInfo userInfo) {
        if (currentUser != null) {
            currentUser.userInfo = userInfo;
        }
        saveUser();
    }

    /**
     * 是否登录过
     * @return boolean
     */
    public boolean hasLogged() {
        return !TextUtils.isEmpty(getUserToken());
    }

    /**
     * 获取登录token
     * 用于判断是否登录过期
     * @return String token
     */
    public String getUserToken() {
        return currentUser == null ? "" : currentUser.userToken;
    }

    public void clearToken() {
        if (currentUser != null) {
            currentUser.userToken = "";
            saveUser();
        }
    }

    public UserInfo getUserInfo() {
        return currentUser == null ? null : currentUser.userInfo;
    }

    public void saveUser() {
        if (currentUser != null) {
            PreferenceUtil.saveObj(context, "currentUser", currentUser);
        } else {
            PreferenceUtil.removeSpKey(context,"currentUser");
        }
    }

    /**
     * 获取当前登录的用户名
     * @return
     */
    public String getUserAccount(){
        return currentUser.account;
    }

    public void clearUserSession(){
        currentUser = null;
        saveUser();
    }

}
